package com.dgut.forum.controller;

import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.config.AppConfig;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.Article;
import com.dgut.forum.model.ArticleReply;
import com.dgut.forum.model.User;
import com.dgut.forum.services.impl.ArticleReplyServiceImpl;
import com.dgut.forum.services.impl.ArticleServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "帖子回复")
@RequestMapping("/articleReply")
public class ArticleReplyController {

    @Autowired
    private ArticleReplyServiceImpl articleReplyService;

    @Autowired
    private ArticleServiceImpl articleService;
    @ApiOperation("新增帖子回复")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId,
                            @ApiParam("回复正文") @RequestParam("content") @NonNull String content){
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("用户被禁言");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED_STATE);
        }

        ArticleReply articleReply=new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReplyService.create(articleReply);

        return AppResult.success();
    }

    @ApiOperation("获取帖子回复")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getReplies(@ApiParam("帖子id") @RequestParam("articleId") @NonNull Long articleId){
        Article article=articleService.selectById(articleId);
        if(article==null){
            log.warn("查询帖子评论,帖子不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        List<ArticleReply> articleReplies = articleReplyService.selectAllReplies(articleId);
        log.info("获取贴评论成功");
        return AppResult.success(articleReplies);
    }
}
